
import { createRouter, createWebHashHistory, RouteRecordRaw, useRouter } from "vue-router";
import NProgress from "nprogress";
import "nprogress/nprogress.css";
import outsideLayout from "./outsideLayout";
import { whiteNameList } from "./constant";
import { useUserStore } from "@/store/modules/user";
import { Storage } from "@/utils/Storage";
import { useDynamicRouting } from "../store/modules/dynamicRouting";
import { itemForm } from "@components/draggable/clounms/accessPath/accessPathSettings/formConfig";
import { Console, log } from "console";
// import { createRouterGuards } from "./router-guards";


// 配置NProgress进度条选项
NProgress.configure({ easing: "ease", speed: 500 });

const routes: Array<RouteRecordRaw | any> = [
  {
    path: "/workplace",
    alias: ['/', '/index'],
    component: () => import("@/layouts/index.vue"),
    name: 'workplace',
    redirect: "/workplace/index",
    // children: [

    //   {//工作台管理
    //     path: "/workplace",
    //     name: "概况",
    //     redirect: '/config/details',
    //     children: [
    //       {
    //         path: "/config/details",
    //         name: "工作台",
    //         component: () => import("@/c-views/config/templateManagement/detail.vue"),
    //       },
    //       {
    //         path: "/workplace/mailbox",
    //         name: "内容-工作流",
    //         component: () => import("@/c-views/WorkPlace/mailbox.vue"),
    //       },
    //     ],
    //   },

    //   {//内容管理
    //     path: "/content",
    //     name: "内容",
    //     redirect: '/content/index',
    //     children: [
    //       {
    //         path: "/content/index",
    //         name: "内容管理",
    //         component: () => import("@/c-views/content/index.vue"),
    //       },
    //       // {
    //       //   path: "/content/recyclingStation",
    //       //   name: "回收站",
    //       //   component: () => import("@/c-views/content/recyclingStation.vue"),
    //       // },
    //       {
    //         path: "/content/pigeonhole",
    //         name: "归档",
    //         component: () => import("@/c-views/content/pigeonhole.vue"),
    //         meta: {
    //           parentPath: '/content/index',
    //         },

    //       },
    //       {
    //         path: "/content/newContent",
    //         name: "内容详情",
    //         component: () => import("@/c-views/content/newContent/index.vue"),
    //         meta: { parentPath: '/content/index' },
    //       },
    //       {
    //         path: "/content/timedTask",
    //         name: "定时任务",
    //         component: () => import("@/c-views/content/timedTask/timedTask.vue"),
    //         meta: { parentPath: '/content/index' },
    //       },
    //     ],
    //   },
    //   // 栏目
    //   {
    //     path: "/colunm",
    //     name: "栏目",
    //     redirect: '/colunm/index',
    //     children: [
    //       {
    //         path: "/colunm/index",
    //         name: "栏目管理",
    //         component: () => import("@/c-views/colunm/index.vue"),
    //       },
    //       {
    //         path: "/colunm/detail",
    //         name: "栏目详情",
    //         component: () => import("@/c-views/colunm/detail.vue"),
    //         meta: { parentPath: '/colunm/index' },
    //       },
    //       {
    //         path: "/colunm/recycleBin",
    //         name: "栏目管理-回收站",
    //         component: () => import("@/c-views/colunm/recycleBin.vue"),
    //         meta: { parentPath: '/colunm/index' },
    //       },
    //       {
    //         path: "/colunm/columnPermission",
    //         name: "栏目权限",
    //         component: () => import("@/c-views/colunm/columnPermission.vue"),
    //         meta: { parentPath: '/colunm/index' },
    //       },
    //       {
    //         path: "/colunm/docPermission",
    //         name: "文档权限",
    //         component: () => import("@/c-views/colunm/docPermission.vue"),
    //         meta: { parentPath: '/colunm/index' },
    //       },
    //     ],
    //   },
    //   // 配置
    //   {
    //     path: "/config",
    //     name: "配置",
    //     'redirect': '/config/siteManage',
    //     children: [
    //       // 站点管理-列表
    //       {
    //         path: "/config/siteManage",
    //         name: "站点管理",
    //         component: () => import("@/c-views/config/siteManage/index.vue"),
    //       },
    //       // 站点管理-详情
    //       {
    //         path: "/config/siteManage/detail",
    //         name: "站点详情",
    //         component: () => import("@/c-views/config/siteManage/detail.vue"),
    //         meta: { parentPath: '/config/siteManage' },
    //       },
    //       // 消息管理
    //       {
    //         path: "/config/message",
    //         name: "消息模板管理",
    //         component: () => import("@/c-views/config/message/index.vue"),
    //       },
    //       // 模板管理
    //       {
    //         path: "/config/templateManagement",
    //         name: "模板管理",
    //         component: () => import("@/c-views/config/templateManagement/index.vue"),
    //       },
    //       // 模板管理详情
    //       {
    //         path: "/config/templateManagement/detail",
    //         name: "模板详情",
    //         component: () => import("@/c-views/config/templateManagement/detail.vue"),
    //       },
    //       //词汇管理
    //       {
    //         path: "/config/wordManages",
    //         name: "词汇管理",
    //         component: () => import("@/layouts/RouteView.vue"),
    //         children: [
    //           {
    //             path: "/config/wordManages/sensitiveWords",
    //             name: "敏感词",
    //             component: () =>
    //               import(
    //                 "@/c-views/config/wordManages/sensitiveWords/index.vue"
    //               ),
    //           },
    //           {
    //             path: "/config/wordManages/searchWorld",
    //             name: "热搜词",
    //             component: () =>
    //               import("@/c-views/config/wordManages/searchWorld/index.vue"),
    //           },
    //           {
    //             path: "/config/wordManages/tagWords",
    //             name: "Tag词",
    //             component: () =>
    //               import("@/c-views/config/wordManages/tagWords/index.vue"),
    //           },
    //           {
    //             path: "/config/wordManages/hotWords",
    //             name: "热词",
    //             component: () =>
    //               import("@/c-views/config/wordManages/hotWords/index.vue"),
    //           },
    //           {
    //             path: "/config/wordManages/hotWords/detail",
    //             name: "热词详情",
    //             component: () =>
    //               import("@/c-views/config/wordManages/hotWords/detail.vue"),
    //             meta: { parentPath: '/config/wordManages/hotWords' },
    //           },
    //         ],
    //       },
    //       //模型管理
    //       {
    //         path: "/config/modelManage",
    //         name: "模型管理",
    //         component: () => import("@/layouts/RouteView.vue"),
    //         children: [
    //           {
    //             path: "/config/modelManage/columnModel",
    //             name: "栏目模型管理",
    //             component: () =>
    //               import("@/c-views/config/modelManage/columnModel/index.vue"),
    //           },
    //           {
    //             path: "/config/modelManage/columnModel/editColumnModel",
    //             name: "编辑栏目模型",
    //             component: () =>
    //               import(
    //                 "@/c-views/config/modelManage/columnModel/editColumnModel.vue"
    //               ),
    //             meta: { parentPath: "/config/modelManage/columnModel" },
    //           }, //
    //           {
    //             path: "/config/modelManage/contentModel",
    //             name: "内容模型管理",
    //             component: () =>
    //               import("@/c-views/config/modelManage/contentModel/index.vue"),
    //           },
    //           {
    //             path: "/config/modelManage/contentType",
    //             name: "内容类型管理",
    //             component: () =>
    //               import("@/c-views/config/modelManage/contentType/index.vue"),
    //           },
    //           {
    //             path: "/config/modelManage/contentModel/editContentModel",
    //             name: "编辑内容模型",
    //             component: () =>
    //               import(
    //                 "@/c-views/config/modelManage/contentModel/editContentModel.vue"
    //               ),
    //             meta: { parentPath: '/config/modelManage/contentModel' }
    //           }, //
    //           {
    //             path: "/config/modelManage/newaddVipmodel",
    //             name: "新建会员模型",
    //             component: () =>
    //               import(
    //                 "@/c-views/config/modelManage/newaddVipmodel/index.vue"
    //               ),
    //           },

    //           {
    //             path: "/config/modelManage/sourceManage",
    //             name: "来源管理",
    //             component: () =>
    //               import("@/c-views/config/modelManage/sourceManage/index.vue"),
    //           },
    //         ],
    //       },
    //       //索引号管理
    //       {
    //         path: "/config/indexNumberManage",
    //         name: "索引号管理",
    //         component: () =>
    //           import("@/c-views/config/indexNumberManage/index.vue"),
    //       },
    //       {
    //         path: "/config/workFlow",
    //         name: "工作流",
    //         component: () => import("@/layouts/RouteView.vue"),
    //         children: [
    //           {
    //             path: "/config/workFlow/index",
    //             name: "工作流列表",
    //             component: () => import("@/c-views/config/workFlow/index.vue"),
    //           },
    //           {
    //             path: "/config/workFlow/detail",
    //             name: "新建工作流",
    //             component: () => import("@/c-views/config/workFlow/detail.vue"),
    //             meta: { parentPath: '/config/workFlow/index' },
    //           },
    //           {
    //             path: "/config/workFlow/auditiIndex",
    //             name: "工作流审核列表",
    //             component: () =>
    //               import("@/c-views/config/workFlow/auditiIndex.vue"),
    //             //
    //           },
    //           {
    //             path: "/config/workFlow/auditDetail",
    //             name: "审核详情",
    //             component: () =>
    //               import("@/c-views/config/workFlow/auditDetail.vue"),
    //             meta: { parentPath: '/config/workFlow/auditiIndex' },
    //           },
    //         ],
    //       },

    //       //定时任务
    //       // {
    //       //   path: "/config/timingTask",
    //       //   name: "定时任务",
    //       //   component: () => import("@/c-views/config/timingTask/index.vue"),
    //       // },
    //       //存储管理
    //       {
    //         path: "/config/storageManage",
    //         name: "存储管理",
    //         component: () => import("@/c-views/config/storageManage/index.vue"),
    //       },
    //       {
    //         path: "/config/blogroll",
    //         name: "链接分组",
    //         component: () => import("@/c-views/config/blogroll/index.vue"),
    //       },
    //       {
    //         path: "/config/blogroll/blogroll",
    //         name: "友情链接",
    //         component: () => import("@/c-views/config/blogroll/blogroll.vue"),
    //       },
    //       {
    //         path: "/config/contentIndex",
    //         name: "内容索引",
    //         component: () => import("@/c-views/config/contentIndex/index.vue"),
    //       },
    //       {
    //         path: "/config/contentIndex/viewTasks",
    //         name: "查看任务",
    //         component: () => import("@/c-views/config/contentIndex/viewTasks/index.vue"),
    //       },
    //       {
    //         path: "/config/contentIndex/viewTasks/detail",
    //         name: "任务失败详情",
    //         component: () => import("@/c-views/config/contentIndex/viewTasks/detail.vue"),
    //       },
    //     ],
    //   },
    //   //会员管理
    //   {
    //     path: "/member",
    //     name: "会员",
    //     redirect: '/member/manage',
    //     children: [
    //       {
    //         path: "/member/manage",
    //         name: "会员管理",
    //         component: () => import("@/c-views/member/manage/index.vue"),
    //       },
    //       {
    //         path: "/member/groupName",
    //         name: "会员组管理",
    //         component: () => import("@/c-views/member/groupName/index.vue"),
    //       },
    //       {
    //         path: "/member/groupName/detail",
    //         name: "组成员管理",
    //         component: () => import("@/c-views/member/groupName/detail.vue"),
    //       },
    //       {
    //         path: "/member/auditedMember",
    //         name: "待审核会员",
    //         component: () => import("@/c-views/member/auditedMember/index.vue"),
    //       },
    //       {
    //         path: "/member/integral",
    //         name: "积分配置",
    //         component: () => import("@/c-views/member/integral/index.vue"),
    //       },
    //     ],
    //   },
    //   //系统

    //   //站内信
    //   {
    //     path: "/mail",
    //     name: "mail",
    //     component: () => import("@/layouts/RouteView.vue"),
    //     children: [
    //       // 站内信
    //       {
    //         path: "/mail/index",
    //         name: "站内信",
    //         component: () =>
    //           import("@/c-views/mail/index.vue"),
    //       },
    //     ],
    //   },
    //   //网站统计
    //   {
    //     path: "/siteStatistics",
    //     name: "统计",
    //     redirect: '/siteStatistics/general',
    //     children: [
    //       // 流量分析
    //       {
    //         path: "/siteStatistics/general",
    //         name: "网站概况",
    //         component: () =>
    //           import("@/c-views/siteStatistics/general/index.vue"),
    //       },
    //       {
    //         path: "/siteStatistics/flowStatictics",
    //         name: "流量分析",
    //         component: () => import("@/layouts/RouteView.vue"),
    //         children: [
    //           // 实时访客
    //           {
    //             path: "/siteStatistics/flowStatictics/index",
    //             name: "实时访客",
    //             component: () =>
    //               import("@/c-views/siteStatistics/flowStatictics/index.vue"),
    //           },
    //           // 趋势分析
    //           {
    //             path: "/siteStatistics/flowStatictics/tendency",
    //             name: "趋势分析",
    //             component: () =>
    //               import("@/c-views/siteStatistics/flowStatictics/tendency.vue"),
    //           },]
    //       }, {
    //         path: "/siteStatistics/sourceStatistics",
    //         name: "来源分析",
    //         component: () => import("@/layouts/RouteView.vue"),
    //         children: [
    //           // 来源类型
    //           {
    //             path: "/siteStatistics/sourceStatistics/index",
    //             name: "来源类型",
    //             component: () =>
    //               import("@/c-views/siteStatistics/sourceStatistics/index.vue"),
    //           },
    //         ]
    //       }, {
    //         path: "/siteStatistics/interviewer",
    //         name: "受访分析",
    //         component: () => import("@/layouts/RouteView.vue"),
    //         children: [
    //           {
    //             path: "/siteStatistics/interviewer/index",
    //             name: "受访页面",
    //             component: () =>
    //               import("@/c-views/siteStatistics/interviewer/index.vue"),
    //           },
    //           {
    //             path: "/siteStatistics/interviewer/entrance",
    //             name: "入口页面",
    //             component: () =>
    //               import("@/c-views/siteStatistics/interviewer/entrance.vue"),
    //           },
    //         ]
    //       }, {// 访客分析 
    //         path: "/siteStatistics/visitorStatistics",
    //         name: "访客分析",
    //         component: () => import("@/layouts/RouteView.vue"),
    //         children: [
    //           {
    //             path: "/siteStatistics/visitorStatistics/visitor",
    //             name: "新老访客",
    //             component: () =>
    //               import("@/c-views/siteStatistics/visitorStatistics/visitor.vue"),
    //           },
    //           {
    //             path: "/siteStatistics/visitorStatistics/network",
    //             name: "网络设备",
    //             component: () =>
    //               import("@/c-views/siteStatistics/visitorStatistics/network.vue"),
    //           },
    //           {
    //             path: "/siteStatistics/visitorStatistics/loyalty",
    //             name: "忠诚度分析",
    //             component: () =>
    //               import("@/c-views/siteStatistics/visitorStatistics/loyalty.vue"),
    //           },
    //           {
    //             path: "/siteStatistics/visitorStatistics/area",
    //             name: "地域分析",
    //             component: () =>
    //               import("@/c-views/siteStatistics/visitorStatistics/area.vue"),
    //           }
    //         ]
    //       },
    //       {// 
    //         path: "/siteStatistics/contentReleaseStatictics",
    //         name: "内容发布分析",
    //         component: () => import("@/layouts/RouteView.vue"),
    //         children: [
    //           {
    //             path: "/siteStatistics/contentReleaseStatictics/column",
    //             name: "contentReleaseStaticticsColumn",
    //             'meta': {
    //               'title': "按栏目"
    //             },
    //             component: () =>
    //               import("@/c-views/siteStatistics/contentReleaseStatictics/column.vue"),
    //           }, {
    //             path: "/siteStatistics/contentReleaseStatictics/users",
    //             name: "按用户",
    //             component: () =>
    //               import("@/c-views/siteStatistics/contentReleaseStatictics/users.vue"),
    //           }, {
    //             path: "/siteStatistics/contentReleaseStatictics/org",
    //             name: "按组织",
    //             component: () =>
    //               import("@/c-views/siteStatistics/contentReleaseStatictics/org.vue"),
    //           }, {
    //             path: "/siteStatistics/contentReleaseStatictics/site",
    //             name: "按站点",
    //             component: () =>
    //               import("@/c-views/siteStatistics/contentReleaseStatictics/site.vue"),
    //           },

    //         ]
    //       }, {// 
    //         path: "/siteStatistics/contentDataStatictics",
    //         name: "内容数据统计",
    //         component: () => import("@/layouts/RouteView.vue"),
    //         children: [
    //           {
    //             path: "/siteStatistics/contentDataStatictics/column",
    //             name: "ontentDataStaticticsColumn",
    //             'meta': {
    //               'title': "按栏目"
    //             },
    //             component: () =>
    //               import("@/c-views/siteStatistics/contentDataStatictics/column.vue"),
    //           }, {
    //             path: "/siteStatistics/contentDataStatictics/singleContent",
    //             name: "按单篇内容",
    //             component: () =>
    //               import("@/c-views/siteStatistics/contentDataStatictics/singleContent.vue"),
    //           },
    //         ]
    //       },
    //],
    //   },
    // ],
  },
  // Layout之外的路由
  ...outsideLayout,
];

const router = createRouter({
  history: createWebHashHistory(),
  routes,
}) as any;
export function resetRouter() {
  router.getRoutes().forEach((route: any) => {
    const { fullPath } = route;
    if (fullPath && !whiteNameList.some((n) => n === fullPath)) {
      router.hasRoute(fullPath) && router.removeRoute(fullPath);
    }
  });
}

let arr = []
// 递归删除数组中符合条件的元素，并返回新数组
const handleData = (array: any[], pid: any) => {
  return array.reduce((prev, item, index) => {
    if (item.menuType == 2) {
      return prev
    }
    prev[index] = item;
    prev[index].realPid = pid;
    if (item.children) {
      prev[index].children = handleData(item.children, item.component.includes('layouts') ? item.id : item.realPid);
    }
    prev = prev.filter((item: any) => item)
    return prev
  }, [])
}
const treeToTile = (treeData: any[], childKey = "children") => {
  //用于拍平数据， 可考虑公用global.ts中使用
  const arr: any[] = [];
  const expanded = (data: any[], com: any) => {
    if (data && data.length > 0) {
      data
        .filter((d) => d)
        .forEach((e) => {
          if (com) {
            if (!com.includes('layouts')) {
              arr.push(e);
            } else {

            }
          } else {
            arr.push(e);
          }
          expanded(e[childKey] || [], e.component);
        });
    }
  };
  expanded(treeData, '');
  return arr;
};
const handleChild = (array: any[], arr: any[]) => {
  array.forEach((item: any) => {
    arr.forEach((data: any) => {
      if (data.realPid == item.id) {
        item.children.push(data);
        item.children.forEach((child: any) => {
          if (child.id == data.parentId) {
            child.children = child.children.filter((c: any) => !(c.id == data.id))
          }
        })
      }
    })
  });
  array.forEach((item: any, index: number) => {
    if (item.realPid && item.parentId != item.realPid) {
      array.splice(index, 1)
    }
  })
}
const addRouteAll = (menu: any[], viewsComponent: any, layoutsComponent: any) => {  //RoleMenu就是接口返回的数据的类型
  menu.forEach(item => {
    // if (item.routePath) {
    //   addRouteItem(item)
    if (item.menuType != 2) {
      item.path = item.routePath;
      item.key = item.routePath;
      item.name = item.menuName;
      item.entryPage = item.entryPage || '';
      if (item.component) {
        if (viewsComponent['../c-views/' + item.component + '.vue'] || layoutsComponent['../' + item.component + '.vue']) {
          item.component = viewsComponent['../c-views/' + item.component + '.vue'] || layoutsComponent['../' + item.component + '.vue']
        } else {
        }
      }
      try {
        item.meta = eval('(' + item.meta + ')');
        item.meta.id = item.id;
      } catch (err) {
        item.meta = { id: item.id }
      }

      if (!item.component) {
        delete item.component
      }
      if (!item.redirect) {
        delete item.redirect
      }

      if (item.children && item.children.length > 0 && item.menuType != 2) {
        item.redirect = item.children && !item.parentId ? item.children[0]?.routePath : undefined;
        addRouteAll(item.children, viewsComponent, layoutsComponent);
      }
    }
  })
}
export async function setupRouter(app: any) {
  // 创建路由守卫
  //createRouterGuards(router, whiteNameList);

  app.use(router);

  // 路由准备就绪后挂载APP实例
  await router.isReady();
}

router.beforeEach((to: any, from: any, next: any) => {
  const userStore = useUserStore();
  if (to.path == '/login') {
    next()
  } else {
    if (Storage.get('ACCESS_TOKEN')) {
      const viewsComponent: Record<string, any> = import.meta.glob("../c-views/**/*.vue");
      const layoutsComponent: Record<string, any> = import.meta.glob("../layouts/**/*.vue");
      let routerList = JSON.parse(JSON.stringify(userStore.userInfo.menues));
      handleData(routerList, '');
      let routers = treeToTile(routerList);
      routers.forEach((item: any, index: number) => {
        if (item.menuType == 2) {
          routers.splice(index, 1)
        }
      })
      handleChild(routers, JSON.parse(JSON.stringify(routers)));
      if (!Storage.get("isLogin")) {
        addRouteAll(routers, viewsComponent, layoutsComponent);
        //setTimeout(() => {
          routers.forEach((item: any) => {
            router.addRoute(item);
          });
          // console.log(location.href, '前置守卫:location.href');
          if(location.href.includes("ken")) {
            const start: any = location.href.indexOf("ken=") + 4
            const ken = location.href.substring(start)
            sessionStorage.ken = ken
          } else {
            // sessionStorage.removeItem('ken')
          }
        let path = sessionStorage.user ? (Storage.get('selectFullPath') && Storage.get('selectFullPath') != '/login' ? Storage.get('selectFullPath') : '/') : '/login';
        next({ path: path, query: Storage.get('selectPathQuery') || {} })
        //}, 40)
      }
      next();
      Storage.set("isLogin", true)
    } else {
      next({ path: '/login' })
    }

  }

});

export default router;
